package cn.minds.capture.dispatch;

import java.io.IOException;
import java.net.Socket;

import cn.minds.capture.dispatch.task.Task;

/**
 * 连接和发送接口
 * */

public abstract class Connect extends Thread {

	private Socket socket;
	CaputureOutputStream outputStream = null;
	CaputureInputStream inputStream = null;
	private TaskManager taskManager;

	public abstract boolean connect();

	public boolean isConnected() {
		return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected()
				&& !socket.isInputShutdown() && !socket.isOutputShutdown();
	}

	public void disConnect() {
		if (isConnected()) {
			try {
				inputStream.close();
				outputStream.close();
				if (!socket.isClosed()) {
					socket.close();
				}
			} catch (IOException ex) {
			}
		}
	}

	public void readCommand() {
		try {
			Protocol.receive(inputStream, this);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendCommand(Task task) {
		if (isConnected()) {
			try {
				Protocol.send(outputStream, task);
			} catch (IOException e) {
				disConnect();
			}
		}
	}

	public void receiveCommand(Task task) {
		taskManager.receiveTask(task);
	}

	public TaskManager getTaskManager() {
		return taskManager;
	}

	public void setTaskManager(TaskManager taskManager) {
		this.taskManager = taskManager;
	}

	public CaputureOutputStream getOutputStream() {
		return outputStream;
	}

	public void setOutputStream(CaputureOutputStream outputStream) {
		this.outputStream = outputStream;
	}

	public CaputureInputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(CaputureInputStream inputStream) {
		this.inputStream = inputStream;
	}

	public Socket getSocket() {
		return socket;
	}

	public void setSocket(Socket socket) {
		this.socket = socket;
	}

}
